const https = require("https"), fs = require("fs");

let bsv = {}, rtp = 1, repNum = 0, tm = null;
const options = {
    hostname: 'www.sudoku-cn.com',
    port: 443,
    path: '/',
    method: 'GET',
    headers:{
        Accept: "*/*",
        Referer: 'https://www.sudoku-cn.com/',
        //Cookie: "__utma=68648851.876249548.1575940386.1575940386.1575943818.2; __utmc=68648851; __utmz=68648851.1575943818.2.2.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; __utmb=68648851.1.10.1575943818; __utmt=1",
        //"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0",
    }
};
function getUrl(){
    options.path = "?l="+rtp+"&t=" + Date.now()
    let req = https.request(options, (res)=>{
        let rd = "";
        //console.log("rc", res.headers);
        res.on('data', (d) => {
            //console.log("data", d);
            rd += d;
        });
        res.on('end', () => {
            console.log("end", rd);
            let rarr = rd.split("@");
            //rarr[1] = rarr[1]|0;
            //if(!(rarr[3] in bsv)) bsv[rarr[3]] = {};
            //if(!(rarr[1] in bsv[rarr[3]])){
            if(!bsv[rarr[1]]){
                bsv[rarr[1]] = rarr[2];
                repNum = 0;
            }else{
                //console.log("comp", bsv[rarr[3]][rarr[1]], rarr[2]);
                console.log("comp", bsv[rarr[1]], rarr[2]);
                repNum++;
                if(repNum > 50){
                    fs.writeFile("./sudu"+rtp+".json", JSON.stringify(bsv), ()=>{
                        console.log("write end")
                    });
                    bsv = {};
                    repNum = 0;
                    rtp++;
                    if(rtp > 4){
                        clearInterval(tm);
                    }
                }
            }
            //console.dir(bsv);
        });
    }).on('error', (e)=>{
        console.log(options.path, e);
    }).end();
}

//let num = 0;
tm = setInterval(()=>{
    /*num++;
    if(num < 1000) getUrl();
    else{
        clearInterval(tm);
        fs.writeFile("./sudu.json", JSON.stringify(bsv), ()=>{
            console.log("write end")
        })
    }*/
    getUrl();
}, 2000)